<!DOCTYPE html>
<html lang=zh-CN>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta property="og:description" content="samuel-24276的博客">
    <meta property="og:type" content="website">
    <meta name="description" content="samuel-24276的博客">
    <meta name="keyword"  content="aircloud">
    <link rel="shortcut icon" href="/myblog/img/favicon.ico">

    <title>
        
        动态库的导入导出宏 - samuel-24276的博客 | samuel-24276&#39;s Blog
        
    </title>

    <!-- Custom CSS -->
    
<link rel="stylesheet" href="/myblog/css/aircloud.css">

    
<link rel="stylesheet" href="/myblog/css/gitment.css">

    <!--<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">-->
    <link href="//at.alicdn.com/t/font_620856_28hi1hpxx24.css" rel="stylesheet" type="text/css">
    <!-- ga & ba script hoook -->
    <script></script>
<meta name="generator" content="Hexo 7.1.1"></head>

<body>

<div class="site-nav-toggle" id="site-nav-toggle">
    <button>
        <span class="btn-bar"></span>
        <span class="btn-bar"></span>
        <span class="btn-bar"></span>
    </button>
</div>

<div class="index-about">
    <i> Like what you do, do what you like </i>
</div>

<div class="index-container">
    
    <div class="index-left">
        
<div class="nav" id="nav">
    <div class="avatar-name">
        <div class="avatar ">
            <img src="/myblog/img/avatar.jpg" />
        </div>
        <div class="name">
            <i>samuel-24276</i>
        </div>
    </div>
    <div class="contents" id="nav-content">
        <ul>
            <li >
                <a href="/myblog/">
                    <i class="iconfont icon-shouye1"></i>
                    <span>主页</span>
                </a>
            </li>
            <li >
                <a href="/myblog/tags">
                    <i class="iconfont icon-biaoqian1"></i>
                    <span>标签</span>
                </a>
            </li>
            <li >
                <a href="/myblog/archives">
                    <i class="iconfont icon-guidang2"></i>
                    <span>存档</span>
                </a>
            </li>
            <li >
                <a href="/myblog/collect/">
                    <i class="iconfont icon-shoucang1"></i>
                    <span>收藏</span>
                </a>
            </li>
            <li >
                <a href="/myblog/about/">
                    <i class="iconfont icon-guanyu2"></i>
                    <span>关于</span>
                </a>
            </li>
            
            <li>
                <a id="search">
                    <i class="iconfont icon-sousuo1"></i>
                    <span>搜索</span>
                </a>
            </li>
            
        </ul>
    </div>
    
        <div id="toc" class="toc-article">
    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%BA%94%E7%94%A8%E8%83%8C%E6%99%AF"><span class="toc-text">应用背景</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#declspec-dllexport"><span class="toc-text">__declspec(dllexport)</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#declspec-dllexport-%E4%B8%8E-def"><span class="toc-text">__declspec(dllexport) 与 .def</span></a></li></ol>
</div>
    
</div>


<div class="search-field" id="search-field">
    <div class="search-bg" id="search-bg"></div>
    <div class="search-container">
        <div class="search-input">
            <span id="esc-search"> <i class="icon-fanhui iconfont"></i></span>
            <input id="search-input"/>
            <span id="begin-search">搜索</span>
        </div>
        <div class="search-result-container" id="search-result-container">

        </div>
    </div>
</div>

        <div class="index-about-mobile">
            <i> Like what you do, do what you like </i>
        </div>
    </div>
    
    <div class="index-middle">
        <!-- Main Content -->
        


<div class="post-container">
    <div class="post-title">
        动态库的导入导出宏
    </div>

    <div class="post-meta">
        <span class="attr">发布于：<span>2021-11-04 17:18:30</span></span>
        
        <span class="attr">标签：/
        
        <a class="tag" href="/myblog/tags/#C++" title="C++">C++</a>
        <span>/</span>
        
        
        </span>
        <span class="attr">访问：<span id="busuanzi_value_page_pv"></span>
</span>
</span>
    </div>
    <div class="post-content no-indent">
        <blockquote>
<p><a target="_blank" rel="noopener" href="https://learn.microsoft.com/zh-cn/cpp/build/reference/lib-reference?view=msvc-170">LIB 引用 | Microsoft Learn</a></p>
</blockquote>
<h1 id="应用背景"><a href="#应用背景" class="headerlink" title="应用背景"></a>应用背景</h1><p>1、解决的问题：</p>
<p>　　考虑下面的需求，使用一个方法，一个是提供者，一个是使用者，二者之间的接口是头文件。头文件中声明了方法，在提供者那里方法应该被声明为__declspec(dllexport)，在使用者那里，方法应该被声明为__declspec(dllimport)。二者使用同一个头文件，作为接口，怎么办呢？</p>
<p>2、解决办法：</p>
<p>　　使用条件编译：定义一个变量，针对提供者和使用者，设置不同的值。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">ifndef</span> DLL_H_</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> DLL_H_</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">ifdef</span> DLLProvider</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> DLL_EXPORT_IMPORT __declspec(dllexport)</span></span><br><span class="line"><span class="meta">#<span class="keyword">else</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> DLL_EXPORT_IMPORT __declspec(dllimport)</span></span><br><span class="line"><span class="meta">#<span class="keyword">endif</span></span></span><br><span class="line"></span><br><span class="line"><span class="function">DLL_EXPORT_IMPORT <span class="type">int</span> <span class="title">add</span><span class="params">(<span class="type">int</span> ,<span class="type">int</span>)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">endif</span></span></span><br></pre></td></tr></table></figure>

<p>declspec(dllexport)声明一个导出函数，是说这个函数要从本DLL导出，我要给别人用。一般用于dll中省掉在DEF文件中手工定义导出哪些函数的一个方法。当然，<strong>如果你的DLL里全是C++的类的话，你无法在DEF里指定导出的函数，只能用declspec(dllexport)导出类</strong>。</p>
<p>declspec(dllimport)声明一个导入函数，是说这个函数是从别的DLL导入，我要用。一般用于使用某个dll的exe中。</p>
<blockquote>
<p>以下内容来自MSDN:</p>
<p><strong>不使用 declspec(dllimport) 也能正确编译代码，但使用 declspec(dllimport) 使编译器可以生成更好的代码</strong>。编译器之所以能够生成更好的代码，是因为它可以确定函数是否存在于 DLL 中，这使得编译器可以生成跳过间接寻址级别的代码，而这些代码通常会出现在跨 DLL 边界的函数调用中。<strong>但是，必须使用 declspec(dllimport)  才能导入 DLL 中使用的变量</strong>。</p>
</blockquote>
<p>初看起来，这段话前面的意思是，不用它也可以正常使用DLL的导出库，但最后一句话又说，必须使用__declspec(dllimport) 才能导入 DLL 中使用的变量这个是什么意思？？</p>
<p>　　那我就来试验一下，假定，你在DLL里只导出一个简单的类，注意，<strong>我假定你已经在项目属性中定义了 <code>SIMPLEDLL_EXPORT</code></strong></p>
<p>SimpleDLLClass.h</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">ifdef</span> SIMPLEDLL_EXPORT</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> DLL_EXPORT __declspec(dllexport)</span></span><br><span class="line"><span class="meta">#<span class="keyword">else</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> DLL_EXPORT</span></span><br><span class="line"><span class="meta">#<span class="keyword">endif</span></span></span><br><span class="line"> </span><br><span class="line"><span class="keyword">class</span> <span class="title class_">DLL_EXPORT</span> SimpleDLLClass</span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">     <span class="built_in">SimpleDLLClass</span>();</span><br><span class="line">     <span class="keyword">virtual</span> ~<span class="built_in">SimpleDLLClass</span>();</span><br><span class="line"></span><br><span class="line">     <span class="function"><span class="keyword">virtual</span> <span class="title">getValue</span><span class="params">()</span> </span>&#123; <span class="keyword">return</span> m_nValue;&#125;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line"> 	<span class="type">int</span> m_nValue;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>　　</p>
<p>SimpleDLLClass.cpp</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;SimpleDLLClass.h&quot;</span></span></span><br><span class="line"> </span><br><span class="line">SimpleDLLClass::<span class="built_in">SimpleDLLClass</span>()</span><br><span class="line">&#123;</span><br><span class="line">	m_nValue=<span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line">SimpleDLLClass::~<span class="built_in">SimpleDLLClass</span>()</span><br><span class="line">&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>　　然后你再使用这个DLL类，在你的APP中include SimpleDLLClass.h时，你的APP的项目不用定义 <code>SIMPLEDLL_EXPORT </code>。所以，DLL_EXPORT 就不会存在了，这个时候，你在APP中，不会遇到问题。这正好对应MSDN上说的<strong>__declspec</strong>(<strong>dllimport</strong>)定义与否都可以正常使用。但我们也没有遇到变量不能正常使用呀。</p>
<p>　　那好，我们改一下SimpleDLLClass,把它的m_nValue改成static,然后在cpp文件中加一行</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> SimpleDLLClass::m_nValue=<span class="number">0</span>;</span><br></pre></td></tr></table></figure>

<p>　　如果你不知道为什么要加这一行，那就回去看看C++的基础。</p>
<p>　　改完之后，再去LINK一下，你的APP，看结果如何， 结果是LINK告诉你找不到这个m_nValue。明明已经定义了，为什么又没有了？？ 肯定是因为我把m_nValue定义为static的原因。但如果我一定要使用Singleton的Design Pattern的话，那这个类肯定是要有一个静态成员，每次LINK都没有，那不是完了？</p>
<p>　　如果你有Platform SDK，用里面的Depend程序看一下，DLL中又的确是有这个m_nValue导出的呀。</p>
<p>　　再回去看看我引用MSDN的那段话的最后一句。 那我们再改一下SimpleDLLClass.h，把那段改成下面的样子:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">ifdef</span> SIMPLEDLL_EXPORT</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> DLL_EXPORT __declspec(dllexport)</span></span><br><span class="line"><span class="meta">#<span class="keyword">else</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> DLL_EXPORT __declspec(dllimport)</span></span><br><span class="line"><span class="meta">#<span class="keyword">endif</span></span></span><br></pre></td></tr></table></figure>

<p>再LINK，一切正常。原来<strong>dllimport</strong>是为了更好的处理类中的静态成员变量的，如果没有静态成员变量，那么这个<strong>__declspec</strong>(<strong>dllimport</strong>)无所谓。</p>
<h1 id="declspec-dllexport"><a href="#declspec-dllexport" class="headerlink" title="__declspec(dllexport)"></a>__declspec(dllexport)</h1><p>将一个函数声名为导出函数，就是说这个函数要被其他程序调用，即<strong>作为DLL的一个对外函数接口</strong>。</p>
<p>通常它和extern  “C”  合用，形式如下：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">extern</span> <span class="string">&quot;C&quot;</span></span><br><span class="line">&#123;</span><br><span class="line">    __declspec(dllexport) <span class="function">RETURN_TYPE <span class="title">FUNCTION</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这是由于在制作DLL导出函数时由于C++存在函数重载，因此__declspec(dllexport)  FUNCTION(int,int)  在DLL会被decorate(装饰)，例如被decorate成为  function_int_int，而且不同的编译器decorate的方法不同，造成了在用GetProcAddress取得FUNCTION地址时的不便，使用extern  “C”时，上述的decorate不会发生，因为C没有函数重载，如此一来被extern”C”修饰的函数，就不具备重载能力。</p>
<blockquote>
<p>以下内容摘自MSDN：</p>
<p>“在 32 位编译器版本中，可以使用__declspec(dllexport) 关键字从 DLL 导出数据、函数、类或类成员函数。__declspec(dllexport)将导出指令添加到对象文件(即obj文件)，<strong>若要导出函数，declspec(dllexport)关键字必须出现在调用约定关键字的左边（如果指定了关键字）</strong>。例如：</p>
<p> declspec(dllexport) void __cdecl Function1(void);</p>
<p><strong>若要导出类中的所有公共数据成员和成员函数，关键字必须出现在类名的左边</strong>，如下所示：</p>
<p> class __declspec(dllexport) CExampleExport : public CObject<br> { … class definition … };</p>
<p>生成 DLL 时，通常创建一个包含正在导出的函数原型和&#x2F;或类的头文件，并将__declspec(dllexport)添加到头文件中的声明。<br>若要提高代码的可读性，请为__declspec(dllexport)定义一个宏并对正在导出的每个符号使用该宏：</p>
<p> #define DllExport  __declspec( dllexport ) </p>
<p>”</p>
</blockquote>
<h1 id="declspec-dllexport-与-def"><a href="#declspec-dllexport-与-def" class="headerlink" title="__declspec(dllexport) 与 .def"></a>__declspec(dllexport) 与 .def</h1><p>模块定义 （.def） 文件是包含一个或多个描述各种 DLL 属性的 Module 语句的文本文件。</p>
<ol>
<li><p>二者的目的都是将公共符号导入到应用程序中或从 DLL 导出函数。</p>
</li>
<li><p><em>添加 declspec(dllexport)是为了提供不使用.def文件从 .EXE 或 .DLL 导出函数的简单方法</em>。</p>
</li>
<li><p>如果不使用 declspec (dllimport) 或 declspec(dllexport) 导出 DLL 函数，则 DLL 需要.def文件。</p>
</li>
<li><p><strong>并不是任何时候选择添加declspec(dllexport)而放弃.def的方式都是好的。如果DLL是提供给VC++用户使用的，只需要把编译DLL时产生的.lib提供给用户，它可以很轻松地调用你的DLL。但是如果DLL是供VB、PB、Delphi用户使用的，那么会产生一个小麻烦。因为VC++对于declspec(dllexport) 声明的函数会进行名称转换</strong>，如下面的函数：</p>
<p><code>__declspec(dllexport) int __stdcall IsWinNT() </code></p>
<p>会转换为<code>IsWinNT@0</code>，这样你在VB中必须这样声明：</p>
<p><code>Declare Function IsWinNT Lib &quot;my.dll&quot; Alias &quot;IsWinNT@0&quot; () As Long </code><br>@的后面的数由于参数类型不同而可能不同。这显然不太方便。所以如果要想避免这种转换，就要使用.def文件方式。</p>
</li>
</ol>
<hr>

        
            <div class="donate-container">
    <div class="donate-button">
        <button id="donate-button">赞赏</button>
    </div>
    <div class="donate-img-container hide" id="donate-img-container">
        <img id="donate-img" src="" data-src="/myblog/img/donate.jpg">
        <p> 感谢鼓励 </p>
    </div>
</div>
        
        <br />
        <div id="comment-container">
        </div>
        <div id="disqus_thread"></div>
        <div id="lv-container"></div>
        <div class="giscus"></div>
    </div>
</div>

    </div>
</div>


<footer class="footer">
    <ul class="list-inline text-center">
        
        

        

        

        
        <li>
            <a target="_blank"  href="https://github.com/samuel-24276">
                            <span class="fa-stack fa-lg">
                                <i class="iconfont icon-github"></i>
                            </span>
            </a>
        </li>
        

        

    </ul>
    
    <p>
        <span>/</span>
        
        <span><a target="_blank" rel="noopener" href="https://github.com/samuel-24276">samuel-24276&#39;s Page</a></span>
        <span>/</span>
        
        <span><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/">北京-未备案</a></span>
        <span>/</span>
        
        <span><a href="#">返回顶部</a></span>
        <span>/</span>
        
    </p>
    
    <p>
        <span id="busuanzi_container_site_pv">
            <span id="busuanzi_value_site_pv"></span>PV
        </span>
        <span id="busuanzi_container_site_uv">
            <span id="busuanzi_value_site_uv"></span>UV
        </span>
        Created By <a target="_blank" rel="noopener" href="https://hexo.io/">Hexo</a>  Theme <a target="_blank" rel="noopener" href="https://github.com/aircloud/hexo-theme-aircloud">AirCloud</a></p>
</footer>




</body>

<script>
    // We expose some of the variables needed by the front end
    window.hexo_search_path = "search.json"
    window.hexo_root = "/myblog/"
    window.isPost = true
</script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>

<script src="/myblog/js/index.js"></script>

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>






    <script type="text/javascript">
       (function() {
           if (typeof LivereTower === 'function') { return; }

           var j, d = document.getElementById('lv-container');

           d.setAttribute('data-id','city');
           d.setAttribute('data-uid' , 'MTAyMC80OTA5OC8yNTU5Mw==');

           j = document.createElement('script');
           j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
           j.async = true;

           d.appendChild(j);
       })();
    </script>
    <noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
    </div>

</html>
